<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
By Chuchu Wu<br />
Type an expression in the following box (e.g. 2.4+5*12-1.2).
<p>
<form action="calculator.php" method="GET">
<INPUT TYPE="text" NAME="expr">
<INPUT TYPE="submit" VALUE="Calculate">
</form>
</p>


<h2>Result</h2>
<?php
if($_GET["expr"]!=Null)
{

$expression = $_GET["expr"];

function Verify($x)
{
if(($x>='0'&& $x<='9') || $x=='+' || $x=='-' || $x=='*' || $x=='/' || $x=='.')return true;
else return false;
}

$i=0;
$valid=true;
while($expression[$i]!=Null)
{
	if(!Verify($expression[$i])) {echo $expression.": Invalid input!"; $valid=false; break;}
	$i++;
}
if($valid)
{
$i--;
if($expression[$i]=='0' && $expression[$i-1]=='/') {echo $expression.": Invalid input!"; $valid=false;}
if($valid)
{
if($expression[$i]>'9' || $expression[$i]<'0') {echo $expression.": Invalid input!"; $valid=false;}
}
}

If($valid)
{
	$Invalid=array("\+\+","\-\-","\*\*","\/\/","\+\*","\+\/","\*\/","\/\*","\-\/","\-\*","\/0\+","\/0\-","\/0\*","\/0\/");
	$j=0;
	while($Invalid[$j]!=Null)
	{	
		if(preg_match("#$Invalid[$j]#",$expression)) 
		{
			echo $expression.": Invalid input!"; 
			$valid=false; 
			break;
		}
		$j++;
	}
}

if($valid == true)
{
eval("\$ans = $expression;");
echo $_GET['expr']." = ".$ans;
}


}
?>
</body>
</html>